package com.gec.filter;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.code.kaptcha.impl.DefaultKaptcha;

public class ImgCodeFilter implements Filter {

	private DefaultKaptcha kt;
	private WebApplicationContext wac;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 主动获取spring容器
		wac = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
		kt = wac.getBean(DefaultKaptcha.class);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// 创建随机文字和图片
		String code = kt.createText();
		req.getSession().setAttribute("imgStand", code);
		BufferedImage img = kt.createImage(code);
		// 对外输出
		OutputStream os = resp.getOutputStream();
		try {
			ImageIO.write(img, "png", os);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			os.flush();
			os.close();
		}

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
